package com.example.springbootneo4j.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.support.JdbcTransactionManager;
import org.springframework.transaction.TransactionManager;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * @author HUAWEI
 * @version 1.0.0
 * @ClassName DataSourceConfig
 * @Description
 * @createTime 2024/11/13 20:09
 */
@Configuration
public class DataSourceConfig {
    @Bean
    public DruidDataSource druidDataSource(@Autowired DataSourceProperties dataSourceProperties){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setAsyncInit(false);
        druidDataSource.setKeepAlive(true);
        druidDataSource.setDefaultAutoCommit(true);
        druidDataSource.setMinIdle(5);
        druidDataSource.setInitialSize(10);
        druidDataSource.setMaxActive(100);
        druidDataSource.setUsername(dataSourceProperties.getUsername());
        druidDataSource.setPassword(dataSourceProperties.getPassword());
        druidDataSource.setUrl(dataSourceProperties.getUrl());
        druidDataSource.setDriverClassName(dataSourceProperties.getDriverClassName());
        try {
            DruidPooledConnection connection = druidDataSource.getConnection();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return druidDataSource;
    }
    @Bean
    public TransactionManager jdbcTransactionManager(DataSource dataSource){
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource);
        transactionManager.setEnforceReadOnly(false);
        return transactionManager;
    }
}
